package project.pianpian.controller;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import project.pianpian.mapper.DemoMapper;
import project.pianpian.entity.Demo;
import project.pianpian.utils.ReturnUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description:
 * Param:
 * return:
 * Author: HSY
 * Date:2022/12/26
 */
@RestController
@Slf4j
@RequestMapping("/main")
public class DemoAPI {
    @Autowired
    private DemoMapper demoMapper;
    @Value("${demo-save-path}")
    String demoPath;



    @GetMapping("/demos/{orderId}")
    public JSONObject getDemoByOrderId(@PathVariable("orderId") int orderId)
    {
        Demo demo = demoMapper.getDemoByOrderId(orderId);
        JSONObject returnJSON = new JSONObject();
        returnJSON.put("demo",demo);
        return ReturnUtils.success(200,"获取demo成功",returnJSON);
    }

    //上传样本同时新建demo表项
    @PostMapping("/uploadDemo")
    public JSONObject addDemo(@RequestParam MultipartFile file, @RequestParam int order_id,HttpServletRequest request)
    {
        if(file == null){
            return ReturnUtils.fail(500,"文件为空");
        }
        String demoUri = upload(request,file,demoPath);
        if(demoUri.equals("-1"))
            return ReturnUtils.fail(500,"文件上传失败");

        int num=demoMapper.addDemo(new Demo(order_id,demoUri,new Date()));

        if(num == 0)
            return ReturnUtils.fail(500,"demo提交失败");

        return ReturnUtils.success(200,"demo提交成功");

    }
    static String upload(HttpServletRequest request,MultipartFile file,String path){

            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID()+suffixName;

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy.MM.dd/");
            String nowDate = simpleDateFormat.format(new Date());
            String realPath = path + nowDate;

            // 如果目录不存在则创建
            File uploadDir = new File(realPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            File localFile = new File(uploadDir+"/"+filename);
            try {
                file.transferTo(localFile);
                String uri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" +
                        "" + nowDate+ "/" + filename;
                return uri;//上传成功，返回保存的文件地址
            }catch (IOException e){
                e.printStackTrace();
                return "-1";
            }
    }

    @GetMapping("/download/{orderId}")
    public void download(@PathVariable("order_id") int order_id, HttpServletResponse response) throws IOException{
        Demo demo = demoMapper.getDemoByOrderId(order_id);
        String uri = demo.getUri();
        URL url = new URL(uri);

        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        OutputStream fis = new BufferedOutputStream(response.getOutputStream());
        byte[] buffer = new byte[1024];
        int count=0;
        while((count = bis.read(buffer,0,1024)) != -1)
        {
            fis.write(buffer, 0, count);
        }
        fis.flush();
        fis.close();
        bis.close();
    }


}





